<template>
  <div class="message">
    id<input type="text" v-model="user.id">
    name<input type="text" v-model="user.name">
<!--    <input type="text" v-model="userId">-->


    <button @click="getConnect">连接{{user.id}}</button>

    <message-list :message="msgList" @send="send" class="left"></message-list>
    <user-list :users="usgList" class="right"></user-list>
  </div>
</template>

<script>
import messageList from "./message-list.vue";
import userList from "./user-list.vue";

export default {
  components: {
    "message-list": messageList,
    "user-list": userList
  },
  data: function() {
    return {
      userId: "",
      user:{id:"",name:"",userId:"",image:"0"},
      msgList: [],
      usgList: [],
      ws: '',
    };
  },
  created: function() {

  },
  methods: {
    getConnect :function () {
      let ws = new WebSocket(`ws://${location.hostname}:3000/ws/chat/${this.user.id}?name=${this.user.name}`);
      this.ws = ws;

      function addToUserList (usgList, user) {
        for (let i = 0, length = usgList.length; i < length; i++) {
          if (usgList[i].id === user.id) {
            return;
          }
        }
        usgList.push(user);
      }

      function addMessage (msgList, msg) {
        msgList.push(msg);
      }

      function removeFromUserList (usgList, user) {
        let target = -1;
        for (let i = 0, length = usgList.length; i < length; i++) {
          if (usgList[i].id === user.id) {
            target = i;
            break;
          }
        }
        if (target >= 0) {
          usgList.splice(target, 1);
        }
      }
      let that = this;
      ws.onmessage = function(event) {
        let data = event.data;
        console.log(data);
        let msg = JSON.parse(data);
        if (msg.type === "list") {
         // if(that.user.userId !== msg.user.userId)

          addToUserList(that.usgList, msg.user);
         // addMessage(that.msgList, msg);

        } else if (msg.type === "join") {

         addToUserList(that.usgList, msg.user);
         // addMessage(that.msgList, msg);
          this.send(JSON.stringify({type:"list",message: "",fromId: that.user.id, toId:msg.user.id,user:that.user,image:that.user.image}))

        } else if (msg.type === "left") {
          removeFromUserList(that.usgList, msg.user);
          addMessage(that.msgList, msg);
        } else if (msg.type === "chat") {
          addMessage(that.msgList, msg);
        }
      };
    },

    send: function(value) {
      console.log(value);


     let result = JSON.stringify({type:"chat",message: value,fromId: this.user.id, toId: this.user.userId,user:this.user})
      console.log(result)
      this.ws.send(result);
    }
  }
};
</script>

<style>
.message {
  margin: 10px 2px;
  min-height: 620px;
  position: relative;
}
.left {
  position: absolute;
  left: 80px;
}
.right {
  position: absolute;
  right: 145px;
}
</style>
